package com.newenergy.wisehome.ui.fragment;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v4.content.PermissionChecker;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.newenergy.light.ble.AdvertiserManager;
import com.newenergy.wisehome.MainActivity;
import com.newenergy.wisehome.R;
import com.newenergy.wisehome.common.helper.LogHelper;
import com.newenergy.wisehome.common.helper.SPUtil;
import com.newenergy.wisehome.common.helper.ToastUtil;
import com.newenergy.wisehome.common.util.LocaleUtil;
import com.newenergy.wisehome.config.AppManager;
import com.newenergy.wisehome.config.Constants;
import com.newenergy.wisehome.data.bean.BallLight;
import com.newenergy.wisehome.data.bean.DeviceCategory;
import com.newenergy.wisehome.data.bean.Family;
import com.newenergy.wisehome.data.bean.SecneMode;
import com.newenergy.wisehome.data.ormlite.dao.BallLightDao;
import com.newenergy.wisehome.data.ormlite.dao.DeviceCategoryDao;
import com.newenergy.wisehome.data.ormlite.dao.FamilyDao;
import com.newenergy.wisehome.data.ormlite.dao.SecneModeDao;
import com.newenergy.wisehome.gateway.common.BLCommonUtils;
import com.newenergy.wisehome.gateway.manager.BLLocalFamilyManager;
import com.newenergy.wisehome.services.BDService;
import com.newenergy.wisehome.ui.widget.CustomDialog;
import com.newenergy.wisehome.ui.widget.LoaddingDialogUtils;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.ButterKnife;
import cn.com.broadlink.base.BLBaseResult;
import me.weyye.hipermission.HiPermission;
import me.yokeyword.fragmentation.SupportFragment;


/**
 * 所有的fragment的基类
 */
public abstract class BaseFragment extends SupportFragment {

    public static final String TAG = "LFX";

    public MainActivity mainActivity;
    private String mPageName = "";
    protected Object data;
    private float mDensity;

    protected TextView mTvMsg;

    protected Family mCurrFamily;
    private List<BallLight> mFamilyGroups;
    public AdvertiserManager mAdvertiserManager;
    private CustomDialog mCustomDialog;
    private PopupWindow mPopupWindow;

    private Dialog mLoadingDialog;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getActivity() instanceof MainActivity) {
            mainActivity = (MainActivity) getActivity();
        }
        mDensity = getContext().getResources().getDisplayMetrics().density;

        if (mAdvertiserManager == null) {
            mAdvertiserManager = AdvertiserManager.getInstance();
//            mAdvertiserManager.setBleScanCallBack(this);
        }

    }


    @Override
    public void onResume() {
        super.onResume();
        mCurrFamily = AppManager.getInstance(getContext()).mCurrFamily;
        showCurrFamily();
        MobclickAgent.onPageStart(mPageName);
    }

    private void showCurrFamily() {
        if (mCurrFamily == null) return;
        mPageName = this.getClass().getSimpleName();
        mFamilyGroups = new BallLightDao(getContext()).getFamilyBallLights(mCurrFamily.getFamilyId(),1);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(mPageName);

    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable
            ViewGroup container, @Nullable Bundle  savedInstanceState) {
        View rootView = inflater.inflate(getLayoutId(), null);
        ButterKnife.bind(this, rootView);
        init(rootView);
        mTvMsg = (TextView) rootView.findViewById(R.id.tv_msg);
        return rootView;
    }


    public abstract int getLayoutId();


    public abstract void init(View rootView);


    public void toast(String message) {
        ToastUtil.myToast(message);
    }

    public void registerEventBus() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    protected void showLoading(String s) {
        mLoadingDialog = LoaddingDialogUtils.createLoadingDialog(getContext(), "");
    }

    protected void dismissLoading() {
        if (mLoadingDialog == null || !mLoadingDialog.isShowing()) {
            return;
        }
        mLoadingDialog.dismiss();
        mLoadingDialog = null;
    }

    protected boolean checkGroupName(String name) {
        DeviceCategoryDao deviceCategoryDao = new DeviceCategoryDao(getContext());
        if (TextUtils.isEmpty(name)) {
            myToast(getString(R.string.tip_room_name_nonull), true);
            return false;
        }

        if (LocaleUtil.getLanguage().startsWith("zh")) {
            if (name.length()<2||name.length()>10){
                ToastUtil.myToast(getString(R.string.tip_room_name_range), true);
                return false;
            }

        }else {
            if (name.length() < 1) {
                ToastUtil.myToast(getString(R.string.tip_room_name_range), true);
                return false;
            }
        }


        if (name.contains("[") || name.contains("#") || name
                .contains("&")) {
            ToastUtil.myToast(getString(R.string.tip_room_name_error), true);
            return false;
        }

        if (mCurrFamily == null) return false;
        DeviceCategory group = deviceCategoryDao.getDeviceCategoryByName(mCurrFamily.getFamilyId(),name);
        if (group != null) {
            myToast(getString(R.string.tip_room_name_used), true);
            return false;
        }
        return true;
    }

    public boolean checkSecneName(String name) {
        SecneModeDao secneModeDao = new SecneModeDao(getContext());
        if (TextUtils.isEmpty(name)) {
            ToastUtil.myToast(getString(R.string.tip_scene_name_nonull), true);
            return false;
        }



        if (LocaleUtil.getLanguage().startsWith("zh")) {
            if (name.length()<2||name.length()>5){
                ToastUtil.myToast(getString(R.string.tip_scene_name_range), true);
                return false;
            }

        }else {
            if (name.length() < 1) {
                ToastUtil.myToast(getString(R.string.tip_scene_name_range), true);
                return false;
            }
        }


        if (mCurrFamily == null) return false;
        SecneMode secneMode = secneModeDao.getSecneByName
                (mCurrFamily.getFamilyId(), name);
        if (secneMode != null) {
            ToastUtil.myToast(getString(R.string.tip_scene_name_used), true);
            return false;
        }
        return true;
    }


    public boolean checkFamilyName(String name) {
        FamilyDao familyDao = new FamilyDao(getContext());
        if (TextUtils.isEmpty(name)) {
            ToastUtil.myToast(getString(R.string.tip_family_name_nonull), true);

            return false;
        }


        if (LocaleUtil.getLanguage().startsWith("zh")) {
            if (name.length()<2||name.length()>5){
                ToastUtil.myToast(getString(R.string.tip_family_name_range), true);
                return false;
            }
        }else {
            if (name.length() < 1) {
                ToastUtil.myToast(getString(R.string.tip_family_name_range), true);
                return false;
            }
        }


        if (name.contains("[") || name.contains("#") || name
                .contains("&")) {
            ToastUtil.myToast(getString(R.string.tip_family_name_error), true);
            return false;
        }
        List<Family> families = familyDao.getAll();
        for (Family family : families) {
            if (family.getName().equals(name)) {
                ToastUtil.myToast(getString(R.string.tip_family_name_used), true);
                return false;
            }
        }
        return true;
    }

    /**
     * 判断语音是否被禁用
     *
     * @return
     */
    public boolean getSpeechEnable() {
        return SPUtil.getBool(Constants.SPEECH_ENABLE, false);
    }

    public void setSpeechEnable(boolean enable) {
        SPUtil.put(Constants.SPEECH_ENABLE, enable);
    }


    /**
     * 自定义土司
     *
     * @param msg
     */
    public void myToast(String msg, boolean isFail) {
        ToastUtil.myToast(msg, isFail);
    }


    public String numToHex(int number) {
        String hex = Integer.toHexString(number).toUpperCase();
        hex = hex.length() % 2 == 0 ? hex : "0" + hex;
        return hex;
    }


    protected int strToInt(String str) {
        try {
            int number = Integer.parseInt(str,16);
            return number;
        } catch (NumberFormatException e) {
            e.printStackTrace();
            return -1;
        }
    }

    public String getByteHex(int b1) {
        String hex = Integer.toString(b1, 16).toUpperCase();
        if (hex.length() < 2) hex = "0" + hex;
        return hex;
    }


    public String numToHexs(int number) {
        String hex = Integer.toHexString(number).toUpperCase();
        if (hex.length()<=2 ) {
            hex = hex.length() % 2 == 0 ? "00"+hex : "000" + hex;
        } else if (hex.length() >= 3) {
            hex = hex.length() % 2 == 0 ? hex : "0" + hex;
        }
        return hex;
    }


    public String intToHex(int number) {
        String hex = Integer.toHexString(number);
        if ((hex.length() % 2) != 0) hex = "0" + hex;
        return hex.toUpperCase();
    }


    public BallLight getGroupByName(String name) {
        for (BallLight group : mFamilyGroups) {
            if (group.getName().equals(name))
                return group;
        }
        LogHelper.i("没有找到相应的数据");
        return null;
    }


    /**
     * 长度 距离
     *
     * @param distance
     * @return
     */
    public int dpToPx(int distance) {
        return (int) (distance * mDensity + 0.5);

    }
    /*** 判断当前线程是否是在主线程*/
    public boolean isMainThread() {
        return Looper.getMainLooper().getThread().getId() == Thread.currentThread().getId();
    }


    @Override
    public void onStop() {
        super.onStop();


    }


    @Override
    public void onStart() {
        super.onStart();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

       /* RefWatcher refWatcher = BaseApp.getRefWatcher(getActivity());
        refWatcher.watch(this);*/
    }


    public void showConfirmDialog(String msg){
        Context context = getContext();
        CustomDialog.Builder builder = new CustomDialog.Builder(context);
        builder.setMessage(msg);
        builder.setMessageSize(18);
        builder.setTitle(getString(R.string.tips));
        builder.setPositiveButton(getString(R.string.btn_confirm), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                confirmOperation();
            }
        });


        builder.setNegativeButton(getString(R.string.btn_cancel),
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create().show();
    }


    public void showPositiveDialog(String msg){
        Context context = getContext();
        CustomDialog.Builder builder = new CustomDialog.Builder(context);
        builder.setMessage(msg);
        builder.setMessageSize(18);
        builder.setTitle(getString(R.string.tips));
        builder.setCanceledOnTouchOutside(false);

        builder.setPositiveButton(getString(R.string.btn_confirm), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                confirmOperation();
            }
        });


        builder.setNegativeButton(null,
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });

        builder.create().show();
    }

    /**
     * 确认对话框确定操作
     */
    protected void confirmOperation() {

    }


    public boolean checkMike() {
        boolean enable=false;
        boolean b=false;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            b = HiPermission.checkPermission(mainActivity, Manifest.permission.RECORD_AUDIO);
        }else {
            b = PermissionChecker.checkSelfPermission(mainActivity, Manifest.permission.RECORD_AUDIO)
                    == PermissionChecker.PERMISSION_GRANTED;
        }

        if (mainActivity.isPermission){
            if (b){
                Intent intent = new Intent(getContext(), BDService.class);
                intent.putExtra("service_cmd","startSpeech");
                getContext().startService(intent);
                enable=true;
                setSpeechEnable(true);
            }else {
                ToastUtil.toast(getString(R.string.no_recording_permission));
                enable=false;
                mainActivity.isPermission=false;
            }
        }else {
            if (getSpeechEnable() && b){
                enable = true;
            } else {
                enable = false;
            }
        }
        return enable;
    }


    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        // 入场动画结束后执行  优化,防动画卡顿
        _mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        _mActivity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        hideSoftInput();
    }


    protected void doBack(){
        _mActivity.onBackPressed();
    }


   /* @Override
    public void foundDevice(String deviceId) {


    }


    @Override
    public void saveDevice(String deviceId) {


    }


    @Override
    public void deleteDevice(String deviceId) {

    }*/


    /*public int checkSerial(String name,int category) {
        if (category == 2) {
            if (!name.startsWith("风扇")&&name.contains("灯"))return -1;
            int number1 = getFanNumber(name);
            if (number1 > 0) {
                return number1;
            }
            return -1;
        } else if (category == 3) {
            if (!name.startsWith("风扇灯"))return -1;
            int number1 = getFanLampNumber(name);
            if (number1 > 0) {
                return number1;
            }
            return -1;
        }

        return -1;

    }

    public int getFanNumber(String name) {
        String number = name.substring(2, name.length());
        int number1 = strToInt(number);
        return number1;
    }


    public int getFanLampNumber(String name) {
        String number = name.substring(3, name.length());
        int number1 = strToInt(number);
        return number1;
    }*/


    /*public String getNewName(String name,List<String> nameList) {
        int count = nameList.size() + 1;
        for (int i=0;i<count;i++) {
            String newName = checkNewName(name, i, nameList);
            if (newName != null) {
                return newName;
            }
        }
        return name;
    }


    public String checkNewName(String name, int index,List<String> nameList) {
        String newName = index < 1 ? name : name  + index  ;
        for (String nameIn : nameList) {
            if (newName.equals(nameIn)) {
                return null;
            }
        }
        return newName;
    }*/


    public String getNewName(String name,List<String> nameList) {
        int count = nameList.size() + 1;
        for (int i=1;i<count;i++) {
            String newName = checkNewName(name, i, nameList);
            if (newName != null) {
                return newName;
            }
        }
        return name;
    }


    public String checkNewName(String name, int index,List<String> nameList) {
        String newName = index < 1 ? name+1 : name  + index  ;
        for (String nameIn : nameList) {
            if (newName.equals(nameIn)) {
                return null;
            }
        }
        return newName;
    }


    public void showDialog(String content){
        CustomDialog.Builder builder = new CustomDialog.Builder(getContext());
        builder.setMessageSize(20);
        builder.setTitle(R.string.tips);
        builder.setMessage(Html.fromHtml(content));
        builder.setPositiveButton(null, (dialog1, which) -> {

        });

        builder.setNegativeButton(null, (dialog, which) -> {

        });

        mCustomDialog = builder.create();
        mCustomDialog.setCanceledOnTouchOutside(true);
        mCustomDialog.show();
    }


    public void dissDialog() {
        if (mCustomDialog != null) {
            mCustomDialog.dismiss();
        }
    }

    public void showPopupWindow(View dropView,int resId) {
        ImageView mTipCommand = (ImageView) View.inflate(getContext(), R.layout.popup_command_tip, null);
        mTipCommand.setBackgroundResource(resId);
        mPopupWindow = new PopupWindow(mTipCommand, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.showAtLocation(dropView, Gravity.CENTER,0,0);

        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = 0.5f;
        getActivity().getWindow().setAttributes(lp);

        mPopupWindow.setOnDismissListener(() -> {
            WindowManager.LayoutParams lp2 = getActivity().getWindow().getAttributes();
            lp.alpha = 1f;
            getActivity().getWindow().setAttributes(lp2);
        });

    }

    /*** 显示BLResult log */
    public void showBLBaseResultLog(BLBaseResult result, String flag) {
        if (result != null) {
            Log.i(TAG, flag + ": succeed = " + result.succeed() + "  error = " + result.getError() + "  msg = " + result.getMsg());
        }
    }

    public boolean checkAppState() {
        if (!BLCommonUtils.checkNetwork(getContext())) {
            Log.e(TAG, "checkAppState:网络不可用 ");
            return false;
        }
        boolean isLogin = BLLocalFamilyManager.getInstance().isLogin;
        if (!isLogin) {
            Log.e(TAG, "checkAppState:没有登录 ");
            return false;
        }
        return true;
    }



}
